if(typeof(item_user_id)!='undefined') var item_user_id=IS_LOGIN;
if(typeof(images_per_page)!='undefined') var images_per_page=10;

var current_ajax_gallery_url=WEB_DIR+'ajax.php?act=upload&code=get_gallery';
var drag_id=0;
var current_page=1;
var	is_submit=false;
var ie6 = jQuery.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
var ie7 = jQuery.browser.msie && /MSIE 7.0/.test(navigator.userAgent);
var page_check_drop={1:'1'};

// Biến dùng để xác định chiều dài và chiều rộng của ảnh trong popup demo list
var demoPreviewWidth = -1;
var demoPreviewHeight = -1;
var demoListName = 'ListItem';
var shopStyle = '';
var showReply = 0;
var showTime = 1;
var showCurrency = 1;
var arrImageUpload = new Array();
var countImage = 1;

if (window.ie6) try {document.execCommand("BackgroundImageCache", false, true);} catch(e){};

jQuery(document).ready(function(){
	//jQuery('body').append('<div id="background"></div>');
	
	jQuery('form[name="PostItemForm"]').addClass("jNice");
								
	current_ajax_gallery_url+=(is_can_edit?'&user_id='+item_user_id:'');
	if(typeof(currency)!='undefined')
	jQuery("span.currency").html(currency[getValueId('currency_id')]);
	
	jQuery("#PostItemForm").submit(function(){//return true;	
		return check_post_submit();	
	});
	
	jQuery("#currency_id").change(function(){jQuery("span.currency").html(currency[getValueId('currency_id')]);});
	jQuery("#first_combo").change(function(){update_all_combo(0);fn_get_filters(jQuery("#first_combo").val())});//Chọn danh mục
	
	jQuery("#second_combo").change(function(){fn_get_filters(jQuery("#second_combo").val())});//Chọn danh mục
	
	jQuery.fn.extend({reset: function() {//function for reset form
		return this.each(function() {jQuery(this).is('form') && this.reset();})}
	});
	check_event_upload();
	
	if(typeof(category_tree) != 'undefined'){		
		update_cat_combo("first_combo",category_tree,'---Chọn danh mục---',first_combo_value);
		update_all_combo(second_combo_value);
	}
	
	for(var index=1;index<=images_per_page;index++){
		check_drop(index);
	}
	check_drag();//alert(file_exists('javascript/tinymce336/jscripts/tiny_mce/tiny_mce.js'));
	
	if(avatar!='')
	{
		DoChangeItemAvatar(avatar);
	}
	
	jQuery('textarea.tinymce').tinymce({
		// Location of TinyMCE script
		script_url : 'javascript/tinymce336/tiny_mce.js',
		// General options
		theme : "advanced",
		//plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
	 	plugins : "safari,fullscreen,inlinepopups,paste",
		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,fontselect,fontsizeselect,forecolor,backcolor,|,link,unlink,pasteword,removeformat,fullscreen",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		theme_advanced_resize_horizontal : false,
		theme_advanced_fonts : "Arial=arial,helvetica,sans-serif;Verdana=verdana,geneva;Times New Roman=times new roman,times;Tahoma=tahoma,arial,helvetica,sans-serif;",
		theme_advanced_font_sizes : "3,4,5,6",
	 
		// Example content CSS (should be your site CSS)
		content_css : "css/content.css",
	 
		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

        force_br_newlines : true,
        force_p_newlines : true,
	 
		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
	
	jQuery('#editItem-editImage').click(function(){
		if(jQuery('#avatar_img_url').val() != '' && jQuery('#avatar_img_server').val() != '')										 
		OpenCropImagePopup('includes/popup/popcropimage.php?isn=' +jQuery('#avatar_img_server').val() + '&ipath=' + jQuery('#avatar_img_url').val());
	});
	
	//if(jQuery('#avatar_img_url').val() != '' && jQuery('#avatar_img_server').val() != '')		
	//jQuery('#editItem-editImage').show();
	
	var requiredMajorVersion = 9; // Major version of Flash required
	var requiredMinorVersion = 0;// Minor version of Flash required
	var requiredRevision = 115;// Revision of Flash required
	
	var hasRightVersion = false;
	
	if (AC_FL_RunContent == 0 || DetectFlashVer == 0) {
		alert("This page requires AC_RunActiveContent.js.");
	} else {
		hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	}
	
	if(jQuery.browser.msie||!hasRightVersion)
	{
		jQuery('#eb_quick_upload').css('display','inline');
		jQuery('#eb_flash_upload').css('display','none');
		jQuery('#eb_quick_mupload').css('display','inline');
		jQuery('#eb_flash_mupload').css('display','none');
		SI.Files.stylizeById('fast_upload_avatar');
	}
	else if(SWFUpload)
	{
		jQuery('#eb_flash_upload').css('display','inline');
		jQuery('#eb_quick_upload').css('display','none');
		jQuery('#eb_flash_mupload').css('display','inline');
		jQuery('#eb_quick_mupload').css('display','none');

		SWFUpload.onload = function () {
			new SWFUpload({
				flash_url : "javascript/swfupload/swfupload.swf",
				upload_url: WEB_DIR + "includes/ajax_action/swfupload.php?cur_user_id=" +IS_LOGIN+ "&user_id=" +item_user_id,
				file_size_limit : "1 MB",
				file_types : "*.jpg;*.jpeg;*.gif;*.png",
				file_types_description : "Images files",
				file_upload_limit : 100,
				file_queue_limit : 0,
				custom_settings : {
					progressTarget : "fsUploadProgress"
					//cancelButtonId : "btnCancel"
				},
				debug: false,
		
				// Button Settings
				button_placeholder_id : "spanButtonPlaceholder",
				button_width: 105,
				button_height: 26,
				button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
				button_cursor: SWFUpload.CURSOR.HAND,
		
				// The event handler functions are defined in handlers.js
				swfupload_loaded_handler : swfUploadLoaded,
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,
				queue_complete_handler : queueComplete,	// Queue plugin event
				
				// SWFObject settings
				minimum_flash_version : "9.0.28",
				swfupload_pre_load_handler : swfUploadPreLoad,
				swfupload_load_failed_handler : swfUploadLoadFailed
			});
            
			new SWFUpload({
				flash_url : "javascript/swfupload/swfupload.swf",
				upload_url: WEB_DIR + "includes/ajax_action/swfupload_multi.php?cur_user_id= " +IS_LOGIN+ "&user_id=" +item_user_id+"&countImage="+countImage,
				file_size_limit : "1 MB",
				file_types : "*.jpg;*.jpeg;*.gif;*.png",
				file_types_description : "Images files",
				file_upload_limit : 100,
				file_queue_limit : 0,
				custom_settings : {
					progressTarget : "fsUploadProgress"
					//cancelButtonId : "btnCancel"
				},
				debug: false,

				// Button Settings
				button_placeholder_id : "spanButtonPlaceholder1",
				button_width: 275,
				button_height: 44,
				button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
				button_cursor: SWFUpload.CURSOR.HAND,

				// The event handler functions are defined in handlers.js
				swfupload_loaded_handler : swfUploadLoaded,
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccessMulti,
				upload_complete_handler : uploadComplete,
				queue_complete_handler : queueComplete,	// Queue plugin event

				// SWFObject settings
				minimum_flash_version : "9.0.28",
				swfupload_pre_load_handler : swfUploadPreLoad,
				swfupload_load_failed_handler : swfUploadLoadFailed
			});
		}
	}
	
	
	if(second_combo_value)//az_filters
	{
		fn_get_filters(second_combo_value);
	}
	else if(first_combo_value)
	{
		fn_get_filters(first_combo_value);
	}
	
	//fn_check_filter();
});
	
function fn_check_filter()
{
	if(item_filters != '')
	{
		var filter_arr = item_filters.split(',');
		
		for(var i in filter_arr)
		{
			if(i != 'inArray')
			{
				jQuery('#filter_' + filter_arr[i]).attr("checked",true);
			}
		}
	}
}

function fn_get_filters(catid)
{
	var sub_cats = 1;
	
	if(typeof(category_tree[catid]) != 'undefined')
	{
		sub_cats = category_tree[catid]['childs'];
	}
	
	var html = '';
	
	if(sub_cats == 1)//Không có sub
	{
		if(typeof(az_filters[catid]) != 'undefined')
		{
			var group_filters = az_filters[catid];
			
			for(var i in group_filters)
			{
				var group_filter = group_filters[i];
				var fgid = group_filter['id'];
				
				html += '<tr>\
							<td valign="top" bgcolor="#FFFFFF" style="color:#00F" align="right">\
								[' + group_filter['id'] + '] ' + group_filter['name'] + '\
								<br />[ <a href="category.html?cmd=filter&fgroup_id='+group_filter['id']+'" target="_blank">Sửa</a> ]\
							</td>\
							<td valign="top"  bgcolor="#FFFFFF" style="color:#F00">';
				
				for(var j in group_filter['filters'])
				{
					var fid = group_filter['filters'][j]['id'];
					
					html += '<div id="f_' + fgid + '">\
								[' + fid + '] <input type="checkbox" value="' + fid + '" name="filter[' + fgid + '][' + fid + ']" id="filter_' + fid + '"><label for="filter_' + fid + '">'+group_filter['filters'][j]['name'] + '</label>\
							</div>';
				}
				
				html += '<div id="nf_' + group_filter['id'] + '"></div><div style="color:#00F;margin:10px 0 5px 0"  align="right"><b>Thuộc tính mới:</b> <input type="text" size="50" id="new_filter_' + group_filter['id'] + '" name="new_filter_' + group_filter['id'] + '"/> <input type="button" value="Thêm" onclick="fn_add_filter(' + group_filter['id'] + ');"/></div></td></tr>';
			}
		}
		
		if(html!='')
		{
			html = '<div style="border:1px solid #ccc;"><div style="margin:15px 15px 10px 15px"><b>Thuộc tính (dùng cho việc lọc sản phẩm)</b></font><br /><br />\
					<table cellspacing="1" cellpadding="5" bgcolor="#99CC00" border="0" width="100%" id="az_group_filter">\
						<tr>\
							<td valign="top" bgcolor="#FFFFFF">\
								<b>Nhóm thuộc tính</b>\
							</td>\
							<td valign="top" bgcolor="#FFFFFF">\
								<b>Thuộc tính</b>\
							</td>\
						</tr>'
						+ 
						html 
						+ '</table>\
						<div style="color:#00F;margin:15px 0 5px 0">\
							<b>Thêm Nhóm thuộc tính mới:</b> <input type="text" size="50" id="new_group_filter" name="new_group_filter"/> <input type="button" value="Thêm" onclick="fn_add_filter_group(' + catid + ')"/>\
						</div>\
						[ <a href="category.html?cmd=edit&id='+catid+'" target="_blank">Quản lý thuộc tính</a> ]\
						</div></div>';
		}
	}
	
	jQuery("#item_filter").html(html);
	
	fn_check_filter();
}

function fn_add_filter_group(catid)
{
	var group_filter_name = jQuery.trim(jQuery('#new_group_filter').val());
	
	if(group_filter_name == '')
	{
		log_faile('Bạn chưa nhập vào tên nhóm thuộc tính.');
		
		jQuery('#new_group_filter').focus();
		return false;
	}
	
	jQuery.ajax({
					type: "POST",
					url: WEB_DIR+"ajax.php?act=item&code=add_group_filter",
					data: {catid: catid,gf_name: group_filter_name},
					dataType: 'json',
					success: function(data)
					{			
						if(data.msg == 'not_login')
						{
							login_error();
							return false;
						}
						else if(data.msg == 'no_perm')
						{
							log_faile('Bạn không có quyền thực hiện chức năng này.',5000);
							return false;
						}
						else if(data.msg != '')
						{
							log_faile(data.msg,5000);
							return false;
						}
						
						else if(data.msg == '')
						{
							html = '<tr>\
							<td valign="top" bgcolor="#FFFFFF" style="color:#00F" align="right">\
								[' + data.id + '] ' + group_filter_name + '\
								<br />[ <a href="category.html?cmd=filter&fgroup_id='+data.id+'" target="_blank">Sửa</a> ]\
							</td>\
							<td valign="top"  bgcolor="#FFFFFF" style="color:#F00">\
								<div id="nf_' + data.id + '"></div>\
								<div style="color:#00F;margin:10px 0 5px 0"  align="right"><b>Thuộc tính mới:</b> <input type="text" size="50" id="new_filter_' + data.id + '" name="new_filter_' + data.id + '"/> <input type="button" value="Thêm" onclick="fn_add_filter(' + data.id + ');"/></div>\
							</td></tr>';
							
							jQuery('#new_group_filter').val('');
							jQuery('#az_group_filter').append(html);
							
							log_success('Thêm nhóm thuộc tính thành công!');
							return ;
						}
					}
				});
}

function fn_add_filter(fgid)
{
	var filter_name = jQuery.trim(jQuery('#new_filter_' + fgid).val());
	
	if(filter_name == '')
	{
		log_faile('Bạn chưa nhập vào tên nhóm thuộc tính.');
		
		jQuery('#new_filter_' + fgid).focus();
		return false;
	}
	
	jQuery.ajax({
				type: "POST",
				url: WEB_DIR+"ajax.php?act=item&code=add_filter",
				data: {fgid: fgid,f_name: filter_name},
				dataType: 'json',
				success: function(data)
				{			
					if(data.msg == 'not_login')
					{
						login_error();
						return false;
					}
					else if(data.msg == 'no_perm')
					{
						log_faile('Bạn không có quyền thực hiện chức năng này.',5000);
						return false;
					}
					else if(data.msg != '')
					{
						log_faile(data.msg,5000);
						return false;
					}
					
					else if(data.msg == '')
					{
						html = '<div id="f_' + data.id + '">\
								[' + data.id + '] <input type="checkbox" value="' + data.id + '" name="filter[' + fgid + '][' + data.id + ']" id="filter_' + data.id + '"><label for="filter_' + data.id + '">'+filter_name + '</label>\
							</div>';
						
						jQuery('#new_filter_' + fgid).val('');
						jQuery('#nf_' + fgid).append(html);
						
						log_success('Thêm thuộc tính thành công!');
						return ;
					}
				}
			});
}

function ajaxFileUpload()
{
	jQuery("#fastUploadProgress").ajaxStart(function(){
		jQuery(this).show();
	})
	.ajaxComplete(function(){
		jQuery(this).hide();
	});

	jQuery.ajaxFileUpload
	(
		{
			url:WEB_DIR+'includes/ajax_action/ajax_upload.php',
			secureuri:false,
			fileElementId:'fast_upload_avatar',
			dataType: 'json',
			success: function (data, status)
			{
				if(typeof(data.error) != 'undefined')
				{
					if(data.error == 'success')
					{
						var avatar 					= new Array();
						
						avatar['img_server']		= data.img_server;
						avatar['img_url']			= data.image_url;
						
						DoChangeItemAvatar(avatar);
					}
					else
					{
						if(data.error=='not_login'){
							alert('Bạn chưa đăng nhập, hãy đăng nhập lại hệ thống trước khi sử dụng chức năng này!');
						}
						else if(data.error=='over_max_size'){
							alert('Ảnh quá dung lượng cho phép!');
						}
						else if(data.error=='ext_invalid'){
							alert('Ảnh bạn chọn không đúng định dạng!');
						}
						else if(data.error=='not_uploaded'){
							alert('Không Upload được file!');
						}
					}
				}
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	)
	
	return false;

}

function OpenCropImagePopup(src)
{
	if(src)
	{
		demoPreviewWidth = 120;
		demoPreviewHeight = 0;
		shopStyle = 'strong';
		showReply = 1;
	
		src += '&pw=' + demoPreviewWidth + '&ph=' + demoPreviewHeight + '&ln=' + demoListName + '&u=' + IS_LOGIN;
		jQuery('#cropIframe').attr('src',src);
		
		
		var pTop 	= jQuery(window).scrollTop() + 20;
		var pLeft 	= (jQuery(window).width() - jQuery('#ajax_list_img').width() ) / 2;
		
		//jQuery.blockUI.defaults.css = {}; 
		jQuery('body').block({ 
			message	: jQuery('#ajax_list_img'),
			css		: 	{	
							border: 'none',
							top:  pTop + 'px', 
							left: pLeft + 'px',
							width: '712px',
							zIndex: '1001',
							display: 'block'
						},
			centerY	: false,
			overlayCSS: {backgroundColor: '#000'}
		});
		
		jQuery('.blockOverlay').click(function(){
			if(!jQuery(this).hasClass('blockElement'))
			{
				ItemUnblockUI();
			}
		});
	}
}

function ItemUnblockUI()
{
	jQuery('#cropIframe').attr('src','');
	jQuery('body').unblock();
}


function update_cat_combo(obj_id, categories, first_text,selected_value)
{
	while (jQuery("#"+obj_id).attr('length')> 0) {
		jQuery("#"+obj_id).children("option").remove();
	}
	
	obj = window.document.getElementById(obj_id);
	var first = true,option = document.createElement('option');
	
	option.value = 0;	
	option.text = first_text;
	option.selected = true;	
	obj.options.add(option);
	optSelected = option;
	
	for(var i in categories)
	{
		if(categories[i].name)//Ktra tên rỗng
		{
			var cat_option 		= document.createElement('option');
			cat_option.value 	= categories[i].id;
			cat_option.text 	= categories[i].name;		
			
			if(selected_value == cat_option.value){
				cat_option.selected = true;
				optSelected = cat_option;
			}
			
			obj.options[obj.options.length] = cat_option;
		}
	}
	
   	obj.selectedIndex = optSelected.index;

	if(jQuery("#"+obj_id).attr('length')<=1){
		jQuery("#"+obj_id).attr("disabled","disabled");
	}
	else{
		jQuery("#"+obj_id).attr("disabled","");
	}
}

function update_all_combo(selected_value){
	var val = getValueId('first_combo');

	if(val!=0)
	{
		var second_categories = category_tree[val]['childs'];
		//if(level_1_catid != val){	
			update_cat_combo('second_combo',second_categories,'---Chọn danh mục cấp 2---',selected_value);
			//level_1_catid = val;
		//}
	}
	else{	
		update_cat_combo('second_combo',{},'---Chọn danh mục cấp 2---',selected_value);
	}
}

function file_exists (url) {
	// Returns true if filename exists  
	// 
	// version: 1004.2314
	// discuss at: http://phpjs.org/functions/file_exists    // +   original by: Enrique Gonzalez
	// +      input by: Jani Hartikainen
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
	// %        note 1: Synchronous so may lock up browser, mainly here for study purposes.     // *     example 1: file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
	// *     returns 1: '123'
	
	var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	if (!req) {throw new Error('XMLHttpRequest not supported');}      
	// HEAD Results are usually shorter (faster) than GET
	req.open('HEAD', url, false);
	req.send(null);
	if (req.status == 200){return true;
	}
	
	return false;
}

function check_file_ext( fileName, fileTypes ){
	
	if (!fileName) return false;
	dots = fileName.split(".");fileType = dots[dots.length-1];
	
	for(i in fileTypes){
		if(!isNaN(i)&&(fileType.toLowerCase() == fileTypes[i].toLowerCase())){
			return true;
		}
	}

	return false;
}

function filterNum(str) {
  re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
  // remove special characters like "$" and "," etc...
  return str.replace(re, "");
}

//TuấnNK add (2008/07/23 13h23) hàm xoá dấu cách thừa
function trimSpace(sourceStr){
	var strTag = sourceStr;
	//alert(strTag);
	var i=0;
	while (i<strTag.length){
		if(strTag.charAt(i)==' ' && strTag.charAt(i+1)==' '){
			str1 = strTag.substring(0,i);
			str2 = strTag.substring(i+1,strTag.length);
			strTag = str1 + str2;
			//alert('gia tri xau Tag1:'+strTag+'\ngia tri xau sourceStr1:'+sourceStr);
		}
		else{
			i++;
		}
	}
	//alert('gia tri xau Tag:'+strTag+'\ngia tri xau sourceStr:'+sourceStr);
	strTag = strTag.replace(new RegExp("&nbsp;" , "g"), "");
	return jQuery.trim(strTag);
}

function get_gallery(img_id){	
	var img_url		= jQuery('#img_'+img_id).attr('lang');
	var server_no 	= jQuery('#img_'+img_id).attr('lang2');
	getValueId('img_new'+current_img_id,'assign',img_id);
	getValueId("i_server"+current_img_id,'assign',server_no);
	getValueId("i_url"+current_img_id,'assign',img_url);
	getValueId("ids_"+current_img_id,'assign',img_id);
	
	var thumb_img = img_server[server_no]+"thumb/80_80/"+img_url;
	//MM_preloadImages(thumb_img);
			
	jQuery('#del_btn'+current_img_id).show();
	jQuery('#img_thumb'+current_img_id).css('background',"url('"+thumb_img+"') no-repeat center");
	
	jsImages[current_img_id] = new Array();
	jsImages[current_img_id]['id'] = img_id;
	jsImages[current_img_id]['img_server'] = server_no;
	jsImages[current_img_id]['img_url'] = img_url;
	
	close_gallery();
};

function ajax_gallery_paging(url_path,div_id,curent_url_path){ 
	current_ajax_gallery_url=url_path;
	jQuery.jCache.maxSize = 10;
    var cache_key = escape(url_path);  
    var current_cache_key = escape(curent_url_path);  
	var divid = '#' + div_id;

	if (jQuery.jCache.hasItem(cache_key)){
		if(current_cache_key!=cache_key)
		jQuery.jCache.setItem(current_cache_key,jQuery(divid).html());
		jQuery(divid).html(jQuery.jCache.getItem(cache_key));
        return;
    }
	
	jQuery.ajax({
	  url: url_path,
	  cache: true,
	  success: function(html){
		if(html!='' && html!='undefined'){
			if(current_cache_key!=cache_key)
			jQuery.jCache.setItem(current_cache_key,jQuery(divid).html());
			jQuery.jCache.setItem(cache_key, html);
			jQuery(divid).html(html);
		}
	  }
	});	
}

function reload_gallery(){
    var cache_key = escape(current_ajax_gallery_url); 
	var divid = '#gallery_content'
	jQuery.jCache.removeItem(cache_key);
	
	jQuery.ajax({
	  url: current_ajax_gallery_url,
	  cache: true,
	  success: function(html){
		if(html!='' && html!='undefined'){			
			jQuery.jCache.setItem(cache_key, html);
			jQuery(divid).html(html);
		}
	  }
	});	
}

function ajax_gallery_search(){
	var cond='';
	var old_url=current_ajax_gallery_url;
	if(getValueId('year')>0 || getValueId('year')==-1){
		cond+='&year='+getValueId('year');
	}
	if(getValueId('month')>0 || getValueId('month')==-1){
		cond+='&month='+getValueId('month');
	}
	if(getValueId('day')>0){
		cond+='&day='+getValueId('day');
	}
	if(getValueId('keywords')){
		cond+='&keywords='+getValueId('keywords');
	}
	
	current_ajax_gallery_url=WEB_DIR+'ajax.php?act=upload&code=get_gallery'+(is_can_edit?'&user_id='+item_user_id:'')+cond;
	ajax_gallery_paging(current_ajax_gallery_url,'gallery_content',old_url);
}

function showRequest(formData, jqForm, options){
	jQuery('#loading').show();
	var fileToUploadValue = jQuery('input[@id=img_upload]').fieldValue();
	
	if (!fileToUploadValue[0] && getValueId('url')==''){
		jQuery('#loading').hide();
		alert('Bạn chưa chọn Ảnh để upload!');
		return false;
	}
	return true;
}

function showResponse(data, statusText){
	jQuery('#loading').hide();

	if (statusText == 'success') {
		if(data.error!='success' && data.url_error!='success'){//Ko up được ảnh
			if(data.error=='not_login'){
				alert('Bạn chưa đăng nhập, hãy đăng nhập lại hệ thống trước khi sử dụng chức năng này!');
			}
			else if(data.error=='over_max_size' || data.url_error=='over_max_size'){
				alert('Ảnh quá dung lượng cho phép!');
			}
			else if(data.error=='ext_invalid'){
				alert('Ảnh bạn chọn không đúng định dạng!');
			}
			else if(data.error=='not_uploaded' ||  data.url_error=='not_uploaded'){
				alert('Không Upload được file!');
			}
			else if(data.url_error=='not_cache_file'){
				alert('Không tạo cache được khi Upload file, mời bạn thử lại sau!');
			}
			
			else if(data.url_error=='not_get_img'){
				alert('Không lấy được ảnh về từ Url bạn nhập vào!');
			}
		}
		else{//Upload thành công!
			var thumb_img = img_server[data.img_server]+"thumb/80_80/"+data.image_url;
			jsImages[current_img_id] = new Array();
			jsImages[current_img_id]['id'] = data.id;
			jsImages[current_img_id]['img_server'] = data.img_server;
			jsImages[current_img_id]['img_url'] = data.image_url;
			
			jQuery("#upload_form").reset();
			jQuery("#thumb").attr("src",no_img_upload);
			//jQuery("#thumb").attr("with",'35');
			//jQuery("#thumb").attr("height",'35');
						
			jQuery("#img_upload").css("backgroundColor","#FFFFFF");
			jQuery("#fake_input").css("backgroundColor","#FFFFFF");
			jQuery("#real_name").html('');
			jQuery('#loading').hide();
			jQuery("#del_btn"+current_img_id).show();
			
			getValueId('img_new'+current_img_id,'assign',data.id);
			getValueId("i_server"+current_img_id,'assign',data.img_server);
			getValueId("i_url"+current_img_id,'assign',data.image_url);
			getValueId("ids_"+current_img_id,'assign',data.id);
						
			jQuery("#img_thumb"+current_img_id).css({background:"url('"+thumb_img+"') no-repeat center"});
			reload_gallery();
			//jQuery("#img_thumb"+current_img_id).css({background:"url('"+thumb_img+"') no-repeat center",backgroundColor:"#fff"});
			//jQuery("#img_thumb"+current_img_id).attr({src:""+thumb_img});
			jQuery.unblockUI();
		}
	} 
	else{
		alert('Không up được ảnh!');
	}
}

function DoChangeItemAvatar(param)
{
	if(param['img_url'] != '') 
	{
		jQuery('.postItemOtherAvatar-img').css('background-image',"none");
		jQuery('#itemAvatar').attr('src',img_server[param['img_server']]+'thumb/272_233/'+param['img_url']);
		jQuery('#itemAvatar').attr('lang','loaded').css('height','174px');		
		
		if(!avatar) avatar = new Array();
		
		avatar['img_server'] 		=  param['img_server'];
		avatar['img_url'] = param['img_url'];
		
		jQuery('#avatar_img_server').val(param['img_server']);
		jQuery('#avatar_img_url').val(param['img_url']);
		
		//jQuery('#editItem-editImage').show();
	}
}

function RemoveAvatarImage()
{
	if(jQuery('#itemAvatar').attr('lang') == 'loaded')
	{
		jQuery('.postItemOtherAvatar-img').css('background','url(style/images/no-images-69x53.jpg) no-repeat center');
		jQuery('#itemAvatar').attr('src',"style/images201005/space.gif");
		jQuery('#itemAvatar').attr('lang','notloaded').css('height','174px');		
		
		jQuery('#avatar_img_server').val('');
		jQuery('#avatar_img_url').val('');
		
		avatar = '';
	}
}

function check_event_upload(){
	jQuery("#upload_form").livequery("submit",function(){		
		jQuery(this).ajaxSubmit({beforeSubmit:showRequest, success:showResponse, url:WEB_DIR+'ajax.php?act=upload&code=item_image'+(is_can_edit?'&user_id='+item_user_id:''), dataType:  'json'});
		return false;
	});
	
	jQuery('#img_upload').livequery("change",function (){ 
		var	fileTypes=['jpg','jpeg','gif','png'];
		
		if(check_file_ext(this.value,fileTypes))
		{
			if(navigator.appName=='Netscape')//FireFox
			{
				var agt=navigator.userAgent.toLowerCase();
				
				if(agt.indexOf("firefox/3")!=-1)//Check version of FF
				{
					var fileSize = this.files.item(0).fileSize;
					var fileName = this.files.item(0).fileName;
					
					if(fileSize > 1024*1024)
					{
						if(fileSize > 1024*1024)
							fileSize=Math.ceil(fileSize/(1024*1024))+' MB';
						else if(fileSize > 1024)
							fileSize=Math.ceil(fileSize/1024)+' KB';	
						else
							fileSize+=' B';
							
						jQuery("#thumb").attr("src",no_img_upload);this.value='';
						getValueId('fake_input','assign','');
						jQuery("#fake_input").css("backgroundColor","yellow");
						jQuery('#url').css("backgroundColor","#FFFFFF");
						jQuery("#real_name").html('');
						alert("Dung lượng ảnh bạn up là ~ "+fileSize+" lớn hơn so với dung lượng ảnh tối đa cho phép là 1 MB!");
						return false;
					}
					else{
						jQuery("#thumb").attr("src",'data:'+this.files.item(0).getAsDataURL());
			
						if(fileSize == 1024*1024)
							fileSize = '1 MB';
						else if(fileSize>1024)
							fileSize=Math.ceil(fileSize/1024)+' KB';	
						else
							fileSize+=' B';
						
						fileName=fileName.substring(0,50);
						getValueId('fake_input','assign',fileName);
						jQuery("#real_name").html('<span title="'+fileName+'">'+fileName+' ('+fileSize+')</span>');
					}
				}
				else{//For FF version <3
					var fileName=this.value,arr = (this.value).split("\\");
					fileName = arr[arr.length-1];
					fileName=fileName.substring(0,50);					
					getValueId('fake_input','assign',fileName);
					jQuery("#real_name").html('<span title="'+fileName+'">'+fileName+'<br />('+fileSize+')</span>');
				}
			}
			else{//MSIE
				
				jQuery("#thumb").attr("src","file:///"+this.value);
				//jQuery("#thumb").attr("with",100);
				//jQuery("#thumb").attr("height",100);
			
				//alert ("file:///"+this.value);
				var fileName=this.value,arr = (this.value).split("\\");
				fileName = arr[arr.length-1];getValueId('fake_input','assign',fileName);
				jQuery("#real_name").html('<span title="'+fileName+'">'+fileName+'</span>');
			}
			jQuery("#fake_input").css("backgroundColor","#FFFFFF");
		}
		else{
			jQuery("#thumb").attr("src",no_img_upload);this.value='';	
			//jQuery("#thumb").attr("with",'35');
			//jQuery("#thumb").attr("height",'35');
			
			getValueId('fake_input','assign','');
			jQuery("#fake_input").css("backgroundColor","yellow");
			alert('Chỉ cho phép định dạnh file '+fileTypes);this.focus();
			jQuery("#real_name").html('');
		}
		
		jQuery('#url').css("backgroundColor","#FFFFFF");
    });
	
	jQuery('#cancel').livequery("click",function(){
		jQuery("#upload_form").reset();
		jQuery("#thumb").attr("src",no_img_upload);
			
		jQuery("#url").css("backgroundColor","#FFFFFF");
		jQuery("#fake_input").css("backgroundColor","#FFFFFF");
		jQuery("#real_name").html('');
		jQuery('#loading').hide();
	});
	jQuery('#url').livequery("change",function(){
		var path=this.value;
		jQuery("#upload_form").reset();		
		getValueId('url','assign',path);
		
		if(path=='' || path.indexOf("http://")==-1){//Check valid path
			jQuery("#thumb").attr("src",no_img);
			
			jQuery(this).css("backgroundColor","yellow");
			jQuery("#real_name").html('');
			alert("URL bạn nhập sai định dạng! Url phải có dạng 'http://www.example.com/abcxyz...'!");
			jQuery('#url').focus();
			return false;
		}
		else{
			jQuery("#thumb").attr("src",path);
			
			jQuery("#real_name").html('');
		}
		jQuery(this).css("backgroundColor","#FFFFFF");
		jQuery("#fake_input").css("backgroundColor","#FFFFFF");
	});
	
	jQuery('#img_upload').livequery("click",function (){
		if (getValueId('fake_input') == 'Chọn ảnh từ máy tính...'){
			getValueId('fake_input','assign','')
		}
    });
}

var old_pos;

function check_drag(){	
	jQuery("#ajax_image_list > .gallery_list_img > .box_img > .get_gallery").livequery(function(){
		jQuery(this).draggable({helper: 'clone',cursor:'move',start:function(){drag_id=this.lang}});			
	});
	jQuery("#ajax_gallery_header").livequery(function(){
		jQuery(this).bind( 'drag', function( event ){
			jQuery('#ajax_gallery').css({top:event.offsetY,left:event.offsetX+151});			
		});
	});
}

function check_drop(index){		
	jQuery("#hilight"+index).livequery(function(){
		jQuery(this).droppable({
			accept: "#ajax_image_list_tuannk > .gallery_list_img > .box_img > .get_gallery",
			//activeClass: 'droppable-active',
			hoverClass: 'droppable-hover',
			tolerance:'pointer',
			drop: function(ev, ui) {
				var img_url		= jQuery('#img_'+drag_id).attr('lang');
				var server_no	= jQuery('#img_'+drag_id).attr('lang2');
				
				var thumb_img = img_server[server_no]+"thumb/80_80/"+img_url;
				
				getValueId('img_new'+this.lang,'assign',drag_id)
				getValueId("i_server"+this.lang,'assign',server_no);
				
				jQuery('#del_btn'+this.lang).show();
				//jQuery("#img_thumb"+this.lang).css({background:"url('"+thumb_img+"') no-repeat center",backgroundColor:"#fff"});
				jQuery("#img_thumb"+this.lang).css({background:"url('"+thumb_img+"') no-repeat center"});
				//jQuery("#img_thumb"+this.lang).attr({src:""+thumb_img});
				
				current_img_id=index;				
			}
		});
	});
}

function mce_embed(val){
	tinyMCE.execCommand('mceInsertContent', false, '['+val+']');
	//tinyMCE.execCommand('mceInsertContent', false, '<a href="##">he he</a>');
}

function browser_gallery(index){	
	var _scrollTop=document.documentElement.scrollTop+140;
	jQuery('#ajax_gallery').css({top:_scrollTop+'px',left:'598px'}).fadeIn("fast");
	ajax_gallery_paging(current_ajax_gallery_url,'gallery_content',current_ajax_gallery_url);	
	current_img_id=index;
	delete _scrollTop;

}

function close_gallery(){
	jQuery('#ajax_gallery').fadeOut("fast");
}

function close_upload(){
	jQuery("#upload_form").reset();
	jQuery("#thumb").attr("src",no_img_upload);
			
	jQuery("#url").css("backgroundColor","#FFFFFF");
	jQuery("#fake_input").css("backgroundColor","#FFFFFF");
	jQuery("#real_name").html('');
	jQuery('#loading').hide();
	jQuery.unblockUI();
	current_img_id=1;
}

function del_image(index){
	getValueId("img_new"+index,'assign',0);
	getValueId("i_server"+index,'assign',0);
	getValueId("i_url"+index,'assign','');
	
	jQuery('#del_btn'+index).hide();
	
	if(getValueId('ids_'+index)){		
		getValueId("image_deleted_"+index,'assign',getValueId('ids_'+index));
		getValueId("ids_"+index,'assign',"");
	}
	
	jQuery("#img_thumb"+index).css({background:"url('"+no_img+"') no-repeat center",backgroundColor:"#fff"});
	//jQuery("#spacer"+index).attr('src','style/images/spacer.gif');		
	//jQuery("#img_thumb"+index).attr({src:no_img});
	
	jsImages[index] = '';
}

function open_upload(index){//Mở box upload ảnh
	close_gallery();
	current_img_id=index;
	jQuery.blockUI({message: jQuery('#ajax_upload')  , overlayCSS: {opacity: 0}, css: { 
			border: 'none',
			width:'400px',left:'598px'
	}});
}

function check_post_submit(){//return true;
	if(is_submit){return false};
	
	var currency=getValueId('currency_id'),name = jQuery.trim(getValueId('name')),sapo=jQuery.trim(getValueId('sapo')), first_combo=getValueId('first_combo'),second_combo=getValueId('second_combo');
	
	getValueId('name','assign',name);
	
	if(name==''){alert('Bạn chưa nhập tiêu đề sản phẩm!');jQuery("#name").focus().removeClass('textAreaPostMsg').addClass('textAreaPostNone');return false;}
	else if( name.length <5){alert('Tiêu đề sản phẩm tối thiểu phải lớn hơn 5 ký tự!');jQuery("#name").focus();return false;}
	
	if(sapo.length>150){
		alert('Mô tả vắn tắt không quá 150 ký tự!');
		jQuery("#sapo").css({display:"inline"});
		jQuery("#sapo").focus();
		return false;
	}	

	tinyMCE.triggerSave();var item_description=jQuery.trim(getValueId('item_description'));
	if(!item_description){alert('Bạn chưa nhập nội dung sản phẩm!');jQuery("#item_description").focus();return false;}
	else if( item_description.length <15){alert('Nội dung sản phẩm tối thiểu phải lớn hơn 15 ký tự!');jQuery("#item_description").focus();return false;}
	
	if(first_combo=='' || first_combo==0){alert('Bạn chưa chọn danh mục');jQuery("#first_combo").focus();return false;}
	
	if(jQuery("#second_combo").attr("disabled") == false && (second_combo=='' || second_combo==0)){
		alert('Bạn chưa chọn danh mục cấp 2');jQuery("#second_combo").focus();return false;
	}
	
	var price		= jQuery.trim(getValueId('price'));
	
	if(!check_price(price)){
		alert('Giá bán chỉ được nhập kiểu số');
		
		jQuery("#price").focus();
		return false;
	}
	
	price 			= parseFloat(price.replace(/\./g,""));
	
	/*if(price==0 || price==''){alert('Với sản phẩm rao bán bạn phải nhập giá!');jQuery("#price").focus();return false;}
	else */
	if(!check_price(price)){alert('Giá bán chỉ được nhập số');jQuery("#price").focus();return false;
	}
	/*else if(currency==1 && (price<100 || price >50000000000)){
		alert('Giá bán phải lớn hơn 100 VNĐ và nhỏ hơn 50 tỷ VNĐ ( 50.000.000.000 VNĐ)');jQuery("#price").focus();return false;
	}
	else if(currency!=1 && (price<1 || price >1000000)){
		alert('Giá bán phải lớn hơn 1 và nhỏ hơn 1 triệu (1.000.000)');jQuery("#price").focus();return false;
	}
	*/
	var price_out = getValueId('price_out');
	
	if(!check_price(price_out)){
		alert('Giá thị trường chỉ được nhập kiểu số');
		
		jQuery("#price_out").focus();
		return false;
	}
	
	price_out = parseFloat(price_out.replace(/\./g,""));
	
	if(price_out>0){
		if(currency==1 && (price_out<100 || price_out >50000000000)){
			alert('Giá thị trường lớn hơn 100 VNĐ và nhỏ hơn 50 tỷ VNĐ ( 50.000.000.000 VNĐ)');jQuery("#price_out").focus();return false;
		}
		else if(currency!=1 && (price<1 || price >1000000)){
			alert('Giá thị trường phải lớn hơn 1 và nhỏ hơn 1 triệu (1.000.000)');jQuery("#price_out").focus();return false;
		}
	}
	
	is_submit=true;return true;		
}

function check_price(e){
  var i = 1;
  var sLength = e.length;
  var str=".0123456789"; 
  
  for(var j=0;j<sLength;j++)
	if(str.indexOf(e.charAt(j))==-1){
		return false;
	}
   return true;
}
function currencyFormat(fld, milSep, decSep, e) {
  var sep = 0;
  var key = '';
  var i = j = 0;
  var len = len2 = 0;
  var strCheck = '0123456789';
  var aux = aux2 = '';
  var whichCode = (window.Event) ? e.which : e.keyCode;

  if (whichCode == 13) return true;  // Enter
  if (whichCode == 8) return true;  // Delete
  key = String.fromCharCode(whichCode);  // Get key value from key code
  if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
  len = fld.value.length;
  for(i = 0; i < len; i++)
  if ((fld.value.charAt(i) != '0')) break;
  aux = '';
  for(; i < len; i++)
  if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
  aux += key;
  len = aux.length;
 // if (len == 0) fld.value = '';
 // if (len == 1) fld.value = '0'+ decSep + '0' + aux;
 // if (len == 2) fld.value = '0'+ decSep + aux;
 // if (len > 2) {
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--) {
      if (j == 3) {
        aux2 += milSep;
        j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    fld.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
    fld.value += aux2.charAt(i);
	
    fld.value += aux.substr(len - 2, len);
	//fld.value += decSep + aux.substr(len - 2, len);
 // }
  return false;
}

function fn_click_show_sapo()
{
	jQuery('#sapo').toggle();
	jQuery('#limit_cha').toggle();
}

function check_total_up_img(){	
	var total = 0;
	for(i=1; i<=100;i++){
		if(document.getElementById("img_new"+i).value>0 || document.getElementById("ids_"+i).value!=""){			
			total = total+1;
		}
	}
	//if(!total&&jQuery('#avatar_img_url').val()) total = 1;
	return total;
}

function sortObject(o) {
    var sorted = {},
    key, a = [];

    for (key in o) {
        if (o.hasOwnProperty(key)) {
                a.push(key);
        }
    }

    a.sort(function(x,y){return x-y;});

    for (key = 0; key < a.length; key++) {
        sorted[a[key]] = o[a[key]];
    }
    return sorted;
}


function embed_img(p1){
	
	position = p1.substring(1,p1.length-1);
	
	if(typeof(jsImages[position]) != 'undefined' && jsImages[position]){
		var thumb_max = 'http://' + img_server[jsImages[position]['img_server']] + 'thumb_max/' + jsImages[position]['img_url'];
		var altText = jQuery('#image_title_' + position).val()?jQuery('#image_title_' + position).val():(' Ảnh số ' + position);
		return '<a href="' + thumb_max + '" alt="Ảnh số ' + (position+1) + ' target="_blank"><img alt="' + altText + '" src="http://' + img_server[jsImages[position]['img_server']] + 'thumb_w/180/' + jsImages[position]['img_url'] + '" style="margin:2px" title="' + altText + '" width="180" /></a>';
	}
	else
	{
		return '';
	} 
}



function checkNum(data) {      // checks if all characters 
var valid = "0123456789,";     // are valid numbers or a "."
var ok = 1;var checktemp;
for (var i=0; i<data.length; i++) {
checktemp = "" + data.substring(i, i+1);
if (valid.indexOf(checktemp) == "-1") return 0;}
return 1;
}

//Add by nhatvt
function open_upload_multi(){//Mở box upload nhiều cùng lúc ảnh
//	close_gallery();
	jQuery.blockUI({message: jQuery('#ajax_uploader-multi')  , overlayCSS: {opacity: 0}, css: {
			border: 'none',
			width:'400px',left:'598px'
	}});
}

function close_upload_multi(){
	jQuery(".qq-upload-list").html('');
	jQuery('#loading').hide();
	jQuery.unblockUI();
}


//Lấy những vị trí chưa có ảnh
function getFreeSlot(){
    var i = 1;
    for (i=1;i<=100;i++){
        if(jQuery("#i_server"+i).val() != 0){
            arrImageUpload[i] = 1;
        }else{
            arrImageUpload[i] = 0;
        }
    }
    return arrImageUpload;
}

/**
 * Đưa ảnh phần multi upload vào list ảnh bên trái
 */
function setToListImage(img_id, imageInfo){
    var arrResult = imageInfo.split(',');
    var id = arrResult[1];
    var image_server = arrResult[2];
    var img_url = arrResult[3];
    
    var thumb_img = img_server[image_server]+"thumb/80_80/"+img_url;

    jsImages[img_id] = new Array();
    jsImages[img_id]['id'] = id;
    jsImages[img_id]['img_server'] = image_server;
    jsImages[img_id]['img_url'] = img_url;

    jQuery("#upload_form").reset();
    jQuery("#thumb").attr("src",no_img_upload);

    jQuery("#img_upload").css("backgroundColor","#FFFFFF");
    jQuery("#fake_input").css("backgroundColor","#FFFFFF");
    jQuery("#real_name").html('');
    jQuery('#loading').hide();
    jQuery("#del_btn"+img_id).show();

    getValueId('img_new'+img_id,'assign',id);
    getValueId("i_server"+img_id,'assign',image_server);
    getValueId("i_url"+img_id,'assign',img_url);
    getValueId("ids_"+img_id,'assign',id);

    jQuery("#img_thumb"+img_id).css({background:"url('"+thumb_img+"') no-repeat center"});
    reload_gallery();
    jQuery.unblockUI();
}